#!/bin/bash
export ORACLE_HOME=/home/oracle/app/oracle/product/11.2.0/dbhome_1
export ORACLE_SID=interlib
export PATH=$ORACLE_HOME/bin:$PATH

LOGFILE="/home/oracle/backup/restore_$(date +%F).log"
exec >> $LOGFILE 2>&1

echo "[$(date '+%F %T')] 开始清理30天前的备份文件..."
find /home/oracle/backup/ -type f -mtime +30 -exec rm -f {} \;
echo "[$(date '+%F %T')] 清理完成。"

echo "[$(date '+%F %T')] 开始挂载数据库..."
sqlplus / as sysdba <<EOF
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
EXIT
EOF
echo "[$(date '+%F %T')] 数据库已挂载。"

# 整库恢复操作，增加下列命令。
# RESTORE DATABASE;


echo "[$(date '+%F %T')] 开始恢复数据库（自动识别并应用增量备份和归档日志）..."
rman target / <<EOF
CATALOG START WITH '/home/oracle/backup/' NOPROMPT;
RECOVER DATABASE;
EXIT
EOF
echo "[$(date '+%F %T')] 数据库恢复完成。"

echo "[$(date '+%F %T')] 尝试打开数据库..."
sqlplus / as sysdba <<EOF
ALTER DATABASE OPEN;
EXIT
EOF
echo "[$(date '+%F %T')] 数据库已打开。"
echo "[$(date '+%F %T')] 数据库已恢复正常！。"